from django.db import models
from datetime import datetime

class User(models.Model):
    ROLE_CHOICES = [
        ('admin', '管理员'),
        ('teacher', '教师'),
        ('student', '学生'),
    ]

    STATUS_CHOICES = [
        ('active', '激活'),
        ('inactive', '禁用'),
    ]

    GENDER_CHOICES = [
        ('M', '男'),
        ('F', '女'),
    ]

    username = models.CharField(max_length=50, unique=True, verbose_name='用户名')
    password = models.CharField(max_length=255, verbose_name='密码')
    email = models.EmailField(max_length=100, unique=True, verbose_name='邮箱')
    real_name = models.CharField(max_length=50, verbose_name='真实姓名')
    phone = models.CharField(max_length=20, blank=True, null=True, verbose_name='手机号')
    gender = models.CharField(max_length=1, choices=GENDER_CHOICES, blank=True, null=True, verbose_name='性别')
    birth_date = models.DateField(blank=True, null=True, verbose_name='出生日期')
    role = models.CharField(max_length=10, choices=ROLE_CHOICES, default='student', verbose_name='角色')
    status = models.CharField(max_length=10, choices=STATUS_CHOICES, default='active', verbose_name='状态')
    avatar = models.CharField(max_length=255, blank=True, null=True, verbose_name='头像图片路径')
    department = models.CharField(max_length=100, blank=True, null=True, verbose_name='院系/部门')
    student_id = models.CharField(max_length=20, blank=True, null=True, verbose_name='学号')
    teacher_id = models.CharField(max_length=20, blank=True, null=True, verbose_name='工号')
    created_at = models.DateTimeField(auto_now_add=True, verbose_name='创建时间')
    updated_at = models.DateTimeField(auto_now=True, verbose_name='更新时间')
    last_login = models.DateTimeField(blank=True, null=True, verbose_name='最后登录时间')

    class Meta:
        db_table = 'users'
        verbose_name = '用户'
        verbose_name_plural = '用户'

    def __str__(self):
        return f"{self.username} - {self.real_name}"

    def set_password(self, raw_password):
        """设置密码 - 明文存储"""
        self.password = raw_password

    def check_password(self, raw_password):
        """验证密码 - 明文比较"""
        return self.password == raw_password

    def update_last_login(self):
        """更新最后登录时间"""
        self.last_login = datetime.now()
        self.save(update_fields=['last_login'])